package com.iamteer.day11;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Cookie
 * 
 * Cookie 只能保存字符串类型数据（非中文），浏览器一般允许存放 300 个 cookie，每个站点最多存放 20 个 cookie
 */
@WebServlet("/CookieDemo")
public class CookieDemo extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CookieDemo() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//创建 cookie 对象，保存会话数据
		Cookie cookie = new Cookie("name", "eric");
//		Cookie cookie2 = new Cookie("email", "eric@qq.com");
		/**
		 * 1. Cookie 路径
		 **/
		//cookie 只有当访问路径是 day12 时才会带上
//		cookie.setPath("/day12");
		
		/**
		 * 2. Cookie 有效时间
		 * 正数：保存到浏览器缓存目录（硬盘），数值表示保存时间（秒）
		 * 负数：保存在内存中，浏览器关闭时清除
		 * 零：删除同名的 cookie
		 */
		cookie.setMaxAge(20);	//保存 20 秒，从最后一次调用起算
//		cookie.setMaxAge(-1);	//只要是负数效果一样，浏览器关闭时清除（会话 cookie）
//		cookie.setMaxAge(0);	//清除同名 cookie
		
		//发送 cookie 信息到浏览器
		response.addCookie(cookie);
//		response.addCookie(cookie2);
		//浏览器会保存
		//浏览器在下次访问时，会带上 cookie 信息
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie c : cookies) {
				String name = c.getName();
				String value = c.getValue();
				System.out.println(name + ":" + value);
			}
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
